package afcp.alumni.action.event;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import afcp.alumni.action.base.EventAction;
import afcp.alumni.action.page.AdminAction;
import afcp.alumni.model.CsvFileProperties;
import afcp.alumni.service.SF;
import afcp.alumni.service.UploadService;

@UrlBinding(UploadMemberFileAction.URL)
public class UploadMemberFileAction extends EventAction {
	
	public static final String URL = "/upload";

	private static final Log logger = LogFactory.getLog(UploadMemberFileAction.class);
	
	private static UploadService uploadService = SF.upload(URL);

	@Override
	public String getUrl() {
		return URL;
	}

	public static String getUploadUrl() {
		return uploadService.getUploadUrl();
	}
	
	private CsvFileProperties file;
	
	public CsvFileProperties getFile() {
		return file;
	}

	public void setFile(CsvFileProperties file) {
		this.file = file;
	}

	@Override
	@DefaultHandler
	public Resolution view() {
		return new RedirectResolution(AdminAction.URL + "?err=1");
	}

	public Resolution uploadcsv() {
		
		logger.info("Action: upload successful. try to read uploaded file.");
		boolean error = false;
		try {
			// Récupérer liste de membres renvoyé : ceux dont l'ajout a échoué.
			// Passer ses membres dans la requête, par exemple via "flash scope" de Stripes
			// pour les afficher sur la JSP (en tant qu'erreur).
			uploadService.readUpload(this.context.getRequest(), file);
		} catch (Exception e) {
			logger.error("Error while reading upload.", e);
			error = true;
		}
		
		return new RedirectResolution(AdminAction.URL + (error ? "?err=1" : ""));
	}

	public Resolution uploadexcel() {
		// TODO Upload excel file code...
		
		// uncomment when it's done.
//		return new RedirectResolution(AdminAction.URL + (error ? "?err=1" : ""));
		return new RedirectResolution(AdminAction.URL + "?err=1");
	}

	@Override
	protected String fromUrl() {
		return AdminAction.URL;
	}

}
